/**
 * 
 */
package com.m7012e.a_remote.commons;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.leoj.utils.Handler;
import com.m7012e.a_remote.communication.Message;
import com.m7012e.a_remote.communication.TcpMessage;

/**
 * @author leoj
 *
 */
public class ARemoteTcpSocket extends Thread{
	private Socket _sock;
	private ObjectOutputStream _output;
	private ObjectInputStream _input;
	private Handler<Message> _messageAnalyzer;

	/**
	 * 
	 */
	public ARemoteTcpSocket() {
		_sock  = new Socket();
		initStream();
	}
	public void setHandler(Handler<Message> analyzer){
		_messageAnalyzer = analyzer;
	}
	private void initStream(){
		try {
			_output = new ObjectOutputStream(_sock.getOutputStream());
			_input = new ObjectInputStream(_sock.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void connect(String address, int port) throws IOException{
		connect(new InetSocketAddress(address, port));
	}
	public void connect(InetSocketAddress address) throws IOException{
		_sock.setSoTimeout(500);
		_sock.connect(address);
	}
	
	public void sendMessage(TcpMessage msg){
		try {
			_output.writeObject(msg);
			_output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		while(true){
			try {
				Object o = _input.readObject();
				if (o instanceof TcpMessage) {
					TcpMessage msg = (TcpMessage) o;
					_messageAnalyzer.handle(msg);
				}else{
					System.out.println("recieved Wrong data -> not a TcpMessage ! ");
					//TODO see if a RuntimeError must be launched here or not ... 
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			
		}
	}
}
